package com.arrogames.rgblabyrinth.game.trigger {
	import com.arrogames.rgblabyrinth.game.EntityCreator;
	import com.arrogames.rgblabyrinth.game.GameState;
	import com.arrogames.rgblabyrinth.game.targeting.PlayerNode;
	
	import ash.core.Engine;
	import ash.tools.ListIteratingSystem;
	
	public class TriggerSystem extends ListIteratingSystem {
		
		private var player:PlayerNode;

		private var creator:EntityCreator;
		
		public function TriggerSystem(creator:EntityCreator) {
			super(TriggerNode, triggerNodeUpdated, triggerNodeAdded);
			this.creator = creator;
		}
		
		override public function addToEngine(engine:Engine):void {
			super.addToEngine(engine);
			engine.getNodeList(PlayerNode).nodeAdded.add(onPlayerAdded);
		}
		
		private function onPlayerAdded(node:PlayerNode):void {
			player = node;
		}	
		
		private function triggerNodeAdded(node:TriggerNode):void {
			trace("got one");
		}
		
		private function triggerNodeUpdated(node:TriggerNode, time:Number):void {
			if (hasPlayer()) {
				if (node.trigger.isInside(
						Math.floor(player.position.x), 
						Math.floor(player.position.y))
				) {
					node.effect.execute(creator);
					if (node.effect.executionsLeft < 1) {
						creator.destroyEntity(node.entity);	
					}
				}
			}
		}
		
		private function hasPlayer():Boolean {
			return player !== null;
		}
	}
}